/*
 * cpu_info.cpp
 *
 *  Created on: Dec 14, 2019
 *      Author: devel
 */

#include <string>
#include <unordered_set>
#include <memory.h>
#include <fstream>
#include <sstream>
#include "../cpu_info.hpp"

namespace license {
    namespace os {
        using namespace std;
        static string get_cpu_vendor() {
            return "UnknownVendor";
        }

        static string get_cpu_brand() {
            return "UnknownBrand";
        }

        static uint32_t get_android_cpu_model() {
            ifstream cpuinfo("/proc/cpuinfo");
            if (!cpuinfo.is_open()) {
                return 0;
            }

            string line;
            while (getline(cpuinfo, line)) {
                if (line.find("Hardware") != string::npos) {
                    istringstream iss(line);
                    string key, value;
                    if (getline(iss, key, ':') && getline(iss, value)) {
                        istringstream value_stream(value);
                        uint32_t model = 0;
                        value_stream >> model;
                        return model;
                    }
                }
            }
            return 0;
        }

        static bool is_hypervisor_set_android() {
            ifstream cpuinfo("/proc/cpuinfo");
            if (!cpuinfo.is_open()) {
                return false;
            }

            string line;
            while (getline(cpuinfo, line)) {
                // 在Android上，虚拟化相关的信息可能出现在"Features"行中
                if (line.find("Features") != string::npos && line.find("hypervisor") != string::npos) {
                    return true;
                }
            }
            return false;
        }

        CpuInfo::CpuInfo() : m_vendor(get_cpu_vendor()), m_brand(get_cpu_brand()) {}

        CpuInfo::~CpuInfo() {}

        bool CpuInfo::is_hypervisor_set() const {
            return is_hypervisor_set_android();
        }

        uint32_t CpuInfo::model() const {
            return get_android_cpu_model();
        }

    }  // namespace os
} /* namespace license */
